<template>
    <div class="bone-padding-10">
        <el-row style="margin-top:10px; margin-bottom: 20px;">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item>系统管理</el-breadcrumb-item>
                <el-breadcrumb-item>角色列表</el-breadcrumb-item>
            </el-breadcrumb>
        </el-row>

        <!--表格-->
        <el-row >
            <el-row>
                <el-col :span='4' v-if='!form.isShow'>
                    <el-button @click='toAdd' size='small' type="primary">新增角色</el-button>
                </el-col>
                <el-col :span='4' v-if='form.isShow'>
                    <el-button @click='form.isShow=false' size='small' type="primary">返回列表</el-button>
                </el-col>

                <el-col :span='4' v-if='!form.isShow'>
                    <el-input size="small" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="table.queryKey" @keyup.enter.native="getTableData">
                    </el-input>
                </el-col>
                <!-- <el-col :span='2' :offset='18' style="text-align:right">
                    <el-button @click='toAdd' size='small' type="primary">新增</el-button>
                </el-col> -->
            </el-row>
            <el-row class="bone-top-10" v-if='!form.isShow'>
                <el-table :data='table.tableData' border stripe style='width:100%' size="small" :highlight-current-row="true" ref="multipleTable">
                    <el-table-column label="编号" prop='roleId'></el-table-column>
                    <el-table-column label="名称" prop='name'></el-table-column>
                    <el-table-column label="描述" prop='description'></el-table-column>
                    <el-table-column label='权限'>
                        <template slot-scope="scope">
                            <el-popover trigger="hover" placement="top" ref='popover1'>
                                <span v-for='(item,index) in scope.row.menus'>
                                    <span v-if='index!=0'>
                                        <span v-if='index%5==0'><br/></span>
                                    </span>
                                    {{item.name}}
                                </span>
                            </el-popover>
                             <el-tag size="medium" v-popover:popover1>查看</el-tag> 
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" prop='createTime'></el-table-column>
                    <el-table-column label="排序" prop='orderNum'></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope='scope'>
                            <el-button @click='modifyRole(scope.row)' type="text">修改</el-button>
                            <el-button @click='toDel(scope.row.roleId)' type="text">删除</el-button>
                            <el-button @click='setMenu(scope.row)' type='text'>设置权限</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination class='bone-top-10 my-el-pagination' @current-change="handleCurrentChange" :current-page="this.table.currentPage" :page-size="this.table.pageSize" layout="total, prev, pager, next, jumper" :total="this.table.rowCount"></el-pagination>
            </el-row>

        </el-row>
        <!--新增/修改 表单-->
        <el-row v-if='form.isShow' :gutter="10" class="bone-top-10">
            <el-col :span='8'>
                <el-card>
                    <div slot='header'>
                        <span>{{form.formTitle}}</span>
                    </div>
                    <el-form :model='form' :rules='form.rules' ref='form' size='small' label-width="80px" label-position="right">
                        <el-form-item label="角色名称" prop="name">
                            <el-input v-model='form.name' placeholder="请输入名称"></el-input>
                        </el-form-item>
                        <el-form-item label="角色描述" prop='description'>
                            <el-input v-model="form.description" placeholder="请输入描述"></el-input>
                        </el-form-item>
                        <el-form-item label='排序' prop="orderNum">
                            <el-input-number :min='1' :max='50' v-model="form.orderNum" @change='orderNumChange' style="width:100%"></el-input-number>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="submitForm('form')" type="primary" :disabled='form.submitDisabled'>保存</el-button>
                            <el-button @click="goBack()" type="primary">返回</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
        </el-row>
        <!--弹窗权限选择-->
        <el-dialog :visible.sync='tree.dialogVisible' width='25%' title='设置权限'>
            <div>
                <el-tree ref='menuTree' node-key="menuId" show-checkbox 
                :data='tree.treeData' :props="tree.defaultProps"
                :default-checked-keys='tree.checkKeys'
                :check-strictly='true'>
                </el-tree>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size='small' @click="tree.dialogVisible = false">取 消</el-button>
                <el-button size='small' type="primary" @click="saveMenus">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import Http from '@/components/utils/httpUtil'
export default {
    data() {
        return {
            form: {
                isShow: false,
                formTitle: '',
                isCreate: true,
                roleId: '',
                name: '',
                description: '',
                orderNum: '',
                submitDisabled: false,
                rules: {
                    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
                    description: [{ required: true, message: '请输入描述', trigger: 'blur' }]
                }
            },
            tree: {
                dialogVisible: false,
                treeData: [],
                defaultProps: {
                    children: "children",
                    label: "name"
                },
                checkKeys: [],
                roleId: ''
            },
            table: {
                tableData: [],
                queryKey: '',
                rowCount: 0,
                currentPage: 1,
                pageSize: 10
            },
        }
    },
    methods: {
        //获取表格数据
        getTableData() {
            let p = {};
            p.start = (this.table.currentPage - 1) * this.table.pageSize;
            p.num = this.table.pageSize;
            p.key = this.table.queryKey;
            Http.fetch('/role/listQuery', p)
                .then(res => {
                    this.table.tableData = res.data.rows;
                    this.table.rowCount = res.data.total;
                })
        },
        //改变页数
        handleCurrentChange(val) {
            this.table.currentPage = val;
            this.getTableData();
        },
        //切换到新增页面
        toAdd() {
            this.form.isShow = true;
            this.form.formTitle = '新增角色';
            this.form.isCreate = true;
            this.form.roleId = ''
            this.form.name = '';
            this.form.orderNum = 1
            this.form.description = ''
            this.form.submitDisabled = false;
        },
        //排序框改变数值
        orderNumChange(val) {
            let num = parseInt(val);
            this.form.orderNum = num;
        },
        //返回表格
        goBack() {
            this.form.isShow = false;
        },
        //修改页面
        modifyRole(row){
            this.form.isShow = true;
            this.form.formTitle = '修改角色';
            this.form.isCreate = false;
            this.form.roleId = row.roleId
            this.form.name = row.name
            this.form.orderNum = row.orderNum
            this.form.description = row.description
            this.form.submitDisabled = false;
        },
        //提交表单
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.form.submitDisabled = true;
                    let p = {};
                    let url = '';
                    //新创建
                    if (this.form.isCreate) {
                        url = '/role/add';
                    } else {
                        url = '/role/modify'
                        p.roleId = this.form.roleId;
                    }
                    p.name = this.form.name;
                    p.orderNum = this.form.orderNum;
                    p.description = this.form.description;
                    Http.fetch(url, p)
                    .then(res => {
                        this.$message({
                            showClose: true,
                            message: res.sucMsg,
                            type: "success"
                        });
                        this.form.submitDisabled = false;
                        this.form.isShow = false;
                        this.getTableData();
                    })
                    .catch(err => {
                        this.form.submitDisabled = false;
                        this.$message({
                            showClose: true,
                            message: err.errMsg,
                            type: "error"
                        });
                    })
                }
            });

        },
        //删除角色
        toDel(roleId){
            this.$confirm('是否确定删除?','提示',{
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
            .then(()=>{
                let p = {}
                p.roleId = roleId;
                return Http.fetch('/role/delete', p)
            })
            .then(res=>{
                this.$message({
                    showClose: true,
                    message: res.sucMsg,
                    type: "success"
                });
                this.getTableData();
            })
            .catch(err=>{
                if(err!='cancel'){
                    this.$message({
                        showClose: true,
                        message: err.errMsg,
                        type: "error"
                    });
                }
            })
        },
        //设置权限
        setMenu(row){
            this.tree.checkKeys = []
            let menuIdList = row.menus.map(item=>{
                return item.menuId;
            })

            //第一是 undefined,设置默认选中项
            if(!this.$refs.menuTree){
                this.tree.checkKeys = menuIdList;
            }
            //后面显示树的时候,就通过 setCheckedKeys 去设置选中项
            else{
                this.$refs.menuTree.setCheckedKeys(menuIdList,true)
            }

            this.tree.dialogVisible = true;
            this.tree.roleId = row.roleId;
            
        },
        //保存权限
        saveMenus(){
            let p = {};
            p.roleId = this.tree.roleId;
            let keys = this.$refs['menuTree'].getCheckedKeys();
            console.log(keys)
            p.menuIdList = keys
            Http.fetch('/role/setMenu',p)
            .then(res=>{
                this.tree.dialogVisible = false;
                this.tree.checkKeys = [];
                this.getTableData();
            })
        },
        //获取所有的权限
        getTreeData(){
            let p = {};
            Http.fetch('/menu/listAll',p)
            .then(res=>{
                let tdata = this.createTree(res.data,0);
                this.tree.treeData = tdata;
            })
        },
        //构建树
        createTree(data,pid){
            pid = pid || 0;
            let list = [];
            data.map(item=>{
                if(item.pid==pid){
                    item.children = this.createTree(data,item.menuId)
                    list.push(item);
                }
            })
            return list;
        }
    
    },
    mounted() {
        this.getTableData();
        this.getTreeData()
    }
}
</script>

<style scoped>

</style>
